package com.example.demo.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class HelloController {

	@RequestMapping("/")
	public String indexHome(HttpServletRequest request, HttpServletResponse response, Model model) {
		String contextPath = request.getServletContext().getContextPath();
		log.info("web  contextPath:{}", contextPath);
		// TomcatEmbeddedContext
		String realPath = request.getServletContext().getRealPath("/");
		// log.info("getCommonDocumentRoot().getAbsoluteFile|{}",
		// getCommonDocumentRoot().getAbsoluteFile());
		log.info("realPathTomcatEmbeddedContext |{}{}", realPath);
		return "indexs";

	}

	@RequestMapping("/hel/id")
	public String hello(HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("uid", "123456789");
		model.addAttribute("name", "Jerry");
		System.out.println(request.getParameter("id"));
		return "show";
	}

	@RequestMapping("/index")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("ds", new Date());
		model.addAttribute("name", "tomcat+JSP+SpringBoot");
		return "index";
	}

	public static void main3(String[] args) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost("http://127.0.0.1:8848/test/img/1.png");
		HttpResponse result;
		try {
			result = httpClient.execute(method);
			if (result.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = result.getEntity();
				InputStream in = entity.getContent();
				FileUtils.copyInputStreamToFile(in, new File("d://1234.jpg"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		/** 请求发送成功，并得到响应 **/
	}

	// org.springframework.boot.web.servlet.server.DocumentRoot
	//private static final String[] COMMON_DOC_ROOTS = { "src/main/webapp", "public", "static" };
	private static final String[] COMMON_DOC_ROOTS = { "/", "public", "static" };

	// TomcatWebServer
	@PostConstruct
	private File getCommonDocumentRoot() {
		for (String commonDocRoot : COMMON_DOC_ROOTS) {
			File root = new File(commonDocRoot);
			System.out.println(root.getAbsolutePath());
			if (root.exists() && root.isDirectory()) {
				return root.getAbsoluteFile();
			}
		}
		return null;

	}

}
